package
{
	import flash.geom.Point;
	import flash.geom.Rectangle;

	public class Chromosome
	{
		static public const SIZE:Number = 25;
		
		public var data:Vector.<Number>;
		
		public function generateRandom():void
		{
			data = new Vector.<Number>();
			
			for (var i:int = 0; i < SIZE; i++) 
			{
				var value:Number = Math.round(Math.random()*2-1);
				data.push(value);
			}
		}
		
		public var fitnessRect:Rectangle;
		
		public function fitness(track:Track):Number
		{
			var currentPos:Point = new Point(5,0);
			for each (var command:Number in data) 
			{
				if(isCrash(currentPos, track))
					break;
					
				currentPos.x += command;	
				currentPos.y++;
			}
			return Math.pow(currentPos.y,3);
		}
		
		public function fitness2(track:Track):Number
		{
			var count:Number = 0;
			var currentPos:Point = new Point(5,0);
			for each (var command:Number in data) 
			{
				if(isCrash(currentPos, track))
					count++;
				
				currentPos.x += command;	
				currentPos.y++;
			}
			return Math.pow(data.length-count,3);
		}
		
		public function isCrash(pos:Point, track:Track):Boolean
		{
			if(pos.x < 0 || pos.x > Population.TRACK_WIDTH)
				return true;
			
			for each (var item:Rectangle in track.items) 
			{
				if(item.contains(pos.x, pos.y))
					return true;
			}
			
			return false;
		}
		
		public function clone():Chromosome
		{
			var clone:Chromosome = new Chromosome();
			clone.data = data;
			
			return clone;
		}
	}
}